import { createRouter, createWebHistory } from 'vue-router'
import { useEmployeeStore } from '@/stores'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      // 登录页
      path: '/login',
      component: () => import('@/views/login/LoginPage.vue')
    },
    {
      // 首页
      path: '/',
      component: () => import('@/views/index/Index.vue')
    },
    {
      // 管理页
      path: '/manage',
      component: () => import('@/views/layout/LayoutContainer.vue'),
      // redirect: '/manage/employees',
      children: [
        {
          path: '/manage/employees',
          component: () => import('@/views/manage/EmployeeManage.vue')
        },
        {
          path: '/manage/employeeRoles',
          component: () => import('@/views/manage/EmployeeRoleManage.vue')
        },
        {
          path: '/manage/permissions',
          component: () => import('@/views/manage/PermissionManage.vue')
        },
        {
          path: '/manage/users',
          component: () => import('@/views/manage/UserManage.vue')
        },
        {
          path: '/manage/bills',
          component: () => import('@/views/manage/BillManage.vue')
        },
        {
          path: '/manage/billShow',
          component: () => import('@/views/manage/BillShow.vue')
        },
        {
          path: '/manage/employee/me',
          component: () => import('@/views/manage/EmployeeShow.vue')
        },
        {
          path: '/manage/employee',
          redirect: '/manage/employee/me',
          component: () => import('@/views/manage/EmployeeShow.vue')
        },
        {
          path: '/manage/employee/password',
          component: () => import('@/views/manage/EmployeePassword.vue')
        }
      ]
    },
    {
      // 正常使用页
      path: '/using',
      component: () => import('@/views/using/UsingPage.vue')
    },
    {
      // 测试使用页
      path: '/usingtest',
      component: () => import('@/views/using/UsingPageTest.vue')
    }
  ]
})

// 登录访问拦截
router.beforeEach(async (to) => {
  // to 要前往的路径，from 来自哪个路径
  const employeeStore = useEmployeeStore()
  const employee = employeeStore.employeeInfo
  // 判断是否登录
  if (to.path !== '/login' && !employee.token) {
    // 删除pinia中保留的数据
    employeeStore.removeEmployeeInfo()
    return '/login'
  }
  return true
  // return false，拦回from的地址页面。return 具体路径或路径对象，拦截到对应的地址
  // return true或undefine放行。可以不写，因为默认情况就是放行
})

export default router
